import LayOptionVmodel from "./LayOptionVmodel.js";
import { logger,tools,runtime } from "./tools.js";



/**Layui单选框 */
class LayRadioVmodel extends LayOptionVmodel {
    constructor(elem) {
        super(elem);
        let tis = this;
        let vm = this.vm;
        if (!this.layFilter) {
            throw new Error("LayRadioVmodel必须有lay-filter属性");
        }

        this.checkFormFilter();
        this.ensureName();     
    }

    /**[override]  从原始dom设置数据 */
    loadForAttr() {
        super.loadForAttr();        
        let elem = this.element;
        let vm = this.vm;
        //初始化
        if ($(elem).val() !== void 0) {
            vm.value($(elem).val().toString());
        }        
        vm.checked($(elem).prop("checked"));
        vm.title($(elem).attr("title"));
    }

    /**[override] */
    init() {
        if(!super.init()) return;
        if (!this.vm.value) {           
            throw new Error("layCheckBox绑定元素必须有value属性");
        }
        let tis = this;
        let vm = this.vm;

        //用户操作时更新vmodel
        runtime.layRadioSlot.onChecked(this.layFilter, function (data) {
            var elem = data.elem; // 获得 checkbox 原始 DOM 对象
            var checked = elem.checked; // 获得 checkbox 选中状态
            var value = elem.value; // 获得 radio 值

            vm.checked(value === vm.value());
        });

        let onchange = function (newValue) {
            tis.updateCheckBox();
        }

        //绑定vmodel到元素
        vm.value.subscribe(onchange, null, "change");        
        vm.title.subscribe(onchange, null, "change");
        vm.checked.subscribe(onchange, null, "change");

        this.updateCheckBox();
        this.inited = true;
    }


    updateCheckBox() {
        let tis = this;
        let vm = this.vm;

        //设置禁用状态
        let disabled = vm.disabled();
        $(tis.element).next().toggleClass("layui-radio-disabled", disabled).toggleClass("layui-disabled", disabled);
        $(tis.element).prop("disabled", disabled);

        //设置title
        $(tis.element).attr("title", vm.title());
        $(tis.element).next().children("div").text(vm.title());

        //设置value
        $(tis.element).val(vm.value());

        //设置选中状态
        let checked = vm.checked();
        $(tis.element).prop("checked", checked);
        $(tis.element).next().toggleClass("layui-form-radioed", checked);
        $(tis.element).next().children('.layui-icon')
            .toggleClass("layui-anim-scaleSpring", checked)
            .toggleClass("layui-icon-circle", !checked)
            .toggleClass("layui-icon-radio", checked);
    }
}

export default LayRadioVmodel;